package edu.neu.javaweb.controller;

import edu.neu.javaweb.bean.Employee;
import edu.neu.javaweb.service.EmployeeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "EmpAddServlet", urlPatterns = {"/pages/emp_add"})
public class EmpAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String job = request.getParameter("job");
        String sex = request.getParameter("sex");
        float sal = Float.parseFloat(request.getParameter("sal"));
        int deptid = Integer.parseInt(request.getParameter("deptId"));
        int mgr = Integer.parseInt(request.getParameter("mgr"));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Timestamp hiredate = null;
        try {
            Date date = format.parse(request.getParameter("hireDate"));
            hiredate = new Timestamp(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Employee emp = new Employee(0, name, job, sex,deptid, hiredate, mgr, sal);
        new EmployeeService().add(emp);
        response.sendRedirect("emp_list");
    }
}
